package com.zwg.git_customview.viewpager2

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.zwg.git_customview.R
import com.zwg.git_customview.viewpagerlooperlayout.utils.SizeUtils

class Viewpager2CircleActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.viewpager2_main2)

        val viewPager: ViewPager2 = findViewById(R.id.viewPager)
        viewPager.adapter = MyPagerAdapter(this)
        viewPager.offscreenPageLimit = 1
        viewPager.setPageTransformer { page, position ->
            val offset = resources.getDimensionPixelOffset(R.dimen.page_margin)
            page.translationX = offset * -position
            Log.d(
                "viewpager2",
                "offset=${offset},position=$position,offset * -position=${offset * -position}"
            )
        }

//        viewPager?.setPageTransformer(
//            MarginPageTransformer(
//                SizeUtils.dip2px(this, 20f)
//            )
//        )
    }

    private class MyPagerAdapter(fragmentActivity: FragmentActivity) :
        FragmentStateAdapter(fragmentActivity) {

        override fun getItemCount(): Int {
            return 3 // 设置总共有10个item
        }

        override fun createFragment(position: Int): Fragment {
            return MyFragment.newInstance(position)
        }
    }

    class MyFragment : Fragment() {

        companion object {
            private const val ARG_POSITION = "position"

            fun newInstance(position: Int): MyFragment {
                val fragment = MyFragment()
                val args = Bundle()
                args.putInt(ARG_POSITION, position)
                fragment.arguments = args
                return fragment
            }
        }

        override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {
            val position = arguments?.getInt(ARG_POSITION) ?: 0
            val rootView = inflater.inflate(R.layout.fragment_item, container, false)
            val tv = rootView.findViewById<TextView>(R.id.tv)
            tv.setText("$position")

            if (rootView != null) {
                // 设置每个item的宽高
                val layoutParams = ViewGroup.LayoutParams(
                    SizeUtils.dip2px(context, 140F),
                    SizeUtils.dip2px(context, 300F)
                )
                rootView.layoutParams = layoutParams
            }
            return rootView
        }
    }
}
